package com.example.examsystem.controller;

import com.example.examsystem.dto.MenuTreeDto;
import com.example.examsystem.dto.PermissionDto;
import com.example.examsystem.dto.PermissionTreeDto;
import com.example.examsystem.service.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/permissions")
@RequiredArgsConstructor
public class PermissionController {

    private final PermissionService permissionService;

    /**
     * 获取当前用户的菜单树
     */
    @GetMapping("/menu-tree")
    public ResponseEntity<List<MenuTreeDto>> getMenuTree() {
        List<MenuTreeDto> menuTree = permissionService.getUserMenuTree();
        return ResponseEntity.ok(menuTree);
    }

    /**
     * 获取当前用户的权限列表
     */
    @GetMapping("/user-permissions")
    public ResponseEntity<List<String>> getUserPermissions() {
        List<String> permissions = permissionService.getUserPermissions();
        return ResponseEntity.ok(permissions);
    }

    /**
     * 检查用户是否有指定权限
     */
    @GetMapping("/check/{permission}")
    public ResponseEntity<Boolean> hasPermission(@PathVariable String permission) {
        try {
            // URL解码权限字符串（因为冒号可能被编码）
            String decodedPermission = java.net.URLDecoder.decode(permission, "UTF-8");
            boolean hasPermission = permissionService.hasPermission(decodedPermission);
            return ResponseEntity.ok(hasPermission);
        } catch (Exception e) {
            log.error("检查权限失败: {}", e.getMessage());
            return ResponseEntity.ok(false);
        }
    }

    /**
     * 获取所有权限树
     */
    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('system:permission:view')")
    public ResponseEntity<List<PermissionTreeDto>> getAllPermissionTree() {
        List<PermissionTreeDto> permissionTree = permissionService.getAllPermissionTree();
        return ResponseEntity.ok(permissionTree);
    }

    /**
     * 获取所有权限列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('system:permission:view')")
    public ResponseEntity<List<PermissionDto>> getAllPermissions() {
        List<PermissionDto> permissions = permissionService.getAllPermissions();
        return ResponseEntity.ok(permissions);
    }

    /**
     * 根据ID获取权限
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:permission:view')")
    public ResponseEntity<PermissionDto> getPermissionById(@PathVariable Long id) {
        PermissionDto permission = permissionService.getPermissionById(id);
        return ResponseEntity.ok(permission);
    }

    /**
     * 创建权限
     */
    @PostMapping
    @PreAuthorize("hasAuthority('system:permission:create')")
    public ResponseEntity<PermissionDto> createPermission(@Valid @RequestBody PermissionDto permissionDto) {
        PermissionDto createdPermission = permissionService.createPermission(permissionDto);
        return ResponseEntity.ok(createdPermission);
    }

    /**
     * 更新权限
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('system:permission:update')")
    public ResponseEntity<PermissionDto> updatePermission(@PathVariable Long id, @Valid @RequestBody PermissionDto permissionDto) {
        PermissionDto updatedPermission = permissionService.updatePermission(id, permissionDto);
        return ResponseEntity.ok(updatedPermission);
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:permission:delete')")
    public ResponseEntity<Void> deletePermission(@PathVariable Long id) {
        permissionService.deletePermission(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 根据类型获取权限列表
     */
    @GetMapping("/type/{type}")
    @PreAuthorize("hasAuthority('system:permission:view')")
    public ResponseEntity<List<PermissionDto>> getPermissionsByType(@PathVariable String type) {
        List<PermissionDto> permissions = permissionService.getPermissionsByType(type);
        return ResponseEntity.ok(permissions);
    }

    /**
     * 获取子权限列表
     */
    @GetMapping("/children/{parentId}")
    @PreAuthorize("hasAuthority('system:permission:view')")
    public ResponseEntity<List<PermissionDto>> getChildPermissions(@PathVariable Long parentId) {
        List<PermissionDto> permissions = permissionService.getChildPermissions(parentId);
        return ResponseEntity.ok(permissions);
    }

    /**
     * 检查权限名称是否存在
     */
    @GetMapping("/exists")
    @PreAuthorize("hasAuthority('system:permission:view')")
    public ResponseEntity<Boolean> existsByName(@RequestParam String name, @RequestParam(required = false) Long excludeId) {
        boolean exists = permissionService.existsByName(name, excludeId);
        return ResponseEntity.ok(exists);
    }
}




